import asyncio
import functools
import importlib
from nicegui import ui, app
import sys
import os

# Add parent directory to path to import from tasks module
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Import ServerHelper from tasks model
from tasks.server_helper import ServerHelper

nav_bar_entrys = []
list_of_tabs = ["tasks", "task_detail", "file", "tree"]

def nav_bar_wrapper(func):

    def common_func():
        with ui.row().classes("w-full"):
            for entry in nav_bar_entrys:
                if entry["title"] is None:
                    continue
                ui.link(entry["title"], target=entry["url"])
            ui.space()

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        common_func()
        return func(*args, **kwargs)

    @functools.wraps(func)
    async def wrapper_async(*args, **kwargs):
        common_func()
        return await func(*args, **kwargs)

    if asyncio.iscoroutinefunction(func):
        return wrapper_async
    return wrapper


# Initialize ServerHelper instance to be used across the application
server_helper = ServerHelper(
    base_url=os.getenv("API_URL", "http://localhost:9010"),
)

# Make server_helper available in the app context
app.server_helper = server_helper

# Import tab modules - using the correct package path
for tab in list_of_tabs:
    mod = importlib.import_module(
        f"ui.tabs.{tab}",  # Changed from rr.ui.tabs to ui.tabs
    )
    page_config = mod.page_config
    for entry in page_config["nav_entry"]:
        # logger.info(entry)
        nav_bar_entrys.append(entry)
        ui.page(entry["url"])(nav_bar_wrapper(entry["function"]))


@ui.page("/")
@nav_bar_wrapper
def ui_main():
    ui.navigate.to("/tasks")


# loading apis
# list_of_apis = ["storage_server", "task_output", "tasks"]
# for api in list_of_apis:
#     mod = importlib.import_module(f"runner.api.{api}")


def main():
    storage_secret = (
        "your_storage_secret_here"  # Replace with your actual storage secret
    )
    ui.run(
        storage_secret=storage_secret,
        show=False,
        dark=False,
        port=9011,
    )


if __name__ in {"__main__", "__mp_main__"}:
    main()
